/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
 function ListNode(val, next) {
      this.val = (val===undefined ? 0 : val)
      this.next = (next===undefined ? null : next)
  }

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    const result = new ListNode(0, null);
    let current = result;
    let tmp = 0;
    while (l1 !== null || l2 !== null || tmp) {
        const value1 = l1 === null ? 0 : l1.val;
        const value2 = l2 === null ? 0 : l2.val;
        const nextVal = value1 + value2 + tmp;
        current.val = nextVal % 10;
        tmp = Math.floor(nextVal  / 10);
        l1 = l1 === null ? null : l1.next;
        l2 = l2 === null ? null : l2.next;
        if (l1 === null && l2 === null && !tmp) {
            break;
        }
        current.next = new ListNode(0, null);
        current = current.next;
    }
    return result;
};

a = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, null)))))
b = new ListNode(9, new ListNode(9, new ListNode(9, null)))
c = addTwoNumbers(a, b);
console.log(c)
while(c) {
    console.log(c.val);
    c = c.next
}